package com.yiqi.liebang.common.rongim;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.suozhang.framework.framework.BaseActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.OpenLocalMapUtil;
import com.yiqi.liebang.common.widget.dialog.ActionSheetDialog;
import com.yiqi.liebang.common.widget.dialog.OnOperItemClickL;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import io.rong.message.LocationMessage;

import static com.luck.picture.lib.tools.PictureFileUtils.APP_NAME;

public class LocationActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, OnOperItemClickL, AMapLocationListener {
    LocationMessage mLocationMessage;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.map)
    MapView mMapView;

    private AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private AMapLocationClient mLocationClient;
    AMapLocation mMapLocation;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_location;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_guide);
        mToolbar.setOnMenuItemClickListener(this);
        initToolBar(mToolbar, "地图", true, true);
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions
                .requestEach(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            initLocationClient();
                            // 用户已经同意该权限
                            Log.d("TAG", permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.d("TAG", permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d("TAG", permission.name + " is denied.");
                        }
                    }
                });


    }

    @Override
    protected void initToolBar(Toolbar toolbar, int resTitle) {
        super.initToolBar(toolbar, resTitle);
    }

    @Override
    protected void initData() {
        mLocationMessage = this.getIntent().getParcelableExtra("loc");
        if (mLocationMessage != null) {
            initMaker(mLocationMessage);
        }
    }

    private void initMaker(LocationMessage location) {
        aMap = mMapView.getMap();
        mUiSettings = aMap.getUiSettings();
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(location.getLat(), location.getLng()));
        markerOption.title(location.getPoi());
        markerOption.visible(true);
        markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.rc_ext_location_marker)));
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(location.getLat(), location.getLng())));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(13));
        aMap.addMarker(markerOption);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
     ActionSheetDialog dialog;
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        final String[] stringItems = {"高德地图", "百度地图"};
         dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.title("选择导航方式")//
                .titleTextSize_SP(14.5f)//
                .show();
        dialog.setListener(new ActionSheetDialog.MyClickListenerInterface() {
            @Override
            public void doCancle() {
                dialog.dismiss();
            }
        });
        dialog.setOnOperItemClickL(this);
        return false;
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                if (OpenLocalMapUtil.isGdMapInstalled()) {
                    if (mLocationMessage != null) {
                        openGaoDeMap(mLocationMessage.getLat(), mLocationMessage.getLng(), mLocationMessage.getPoi());
                    }
                } else {
                    showMsg("您还未安装高德地图！");
                }
                break;
            case 1:
                if (OpenLocalMapUtil.isBaiduMapInstalled()) {
                    openBaiduMap(
                            mMapLocation != null ? mMapLocation.getLatitude() : null,
                            mMapLocation != null ? mMapLocation.getLongitude() : null,
                            mMapLocation != null ? mMapLocation.getPoiName() : null,
                            mLocationMessage.getLat(),
                            mLocationMessage.getLng(),
                            mLocationMessage.getPoi());
                } else {
                    showMsg("您还未安装百度地图！");
                }
                break;
        }
        if (dialog!=null){
            dialog.dismiss();
        }
    }

    private void openGaoDeMap(double dlat, double dlon, String dname) {
        try {

            String uri = OpenLocalMapUtil.getGdMapUri(APP_NAME,
                    mMapLocation != null ? String.valueOf(mMapLocation.getLatitude()) : null,
                    mMapLocation != null ? String.valueOf(mMapLocation.getLongitude()) : null,
                    mMapLocation != null ? mMapLocation.getPoiName() : null,
                    String.valueOf(dlat),
                    String.valueOf(dlon),
                    dname);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.autonavi.minimap");
            intent.setData(Uri.parse(uri));
            startActivity(intent); //启动调用
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openBaiduMap(double slat, double slon, String sname,
                              double dlat, double dlon, String dname) {
        try {

            double[] sLocation = OpenLocalMapUtil.gaoDeToBaidu(slat, slon);
            double[] dLocation = OpenLocalMapUtil.gaoDeToBaidu(dlat, dlon);
            String uri = OpenLocalMapUtil.getBaiduMapUri(String.valueOf(sLocation[0]), String.valueOf(sLocation[1]), sname,
                    String.valueOf(dLocation[0]), String.valueOf(dLocation[1]), dname, "", "");
            Intent intent = Intent.parseUri(uri, 0);
            startActivity(intent); //启动调用
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initLocationClient() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听，这里要实现AMapLocationListener接口，AMapLocationListener接口只有onLocationChanged方法可以实现，用于接收异步返回的定位结果，参数是AMapLocation类型。
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2 * 1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {

            mMapLocation = aMapLocation;

        } else {
            showMsg("定位失败" + aMapLocation);
        }

    }
}
